package com.xh.shuati.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.xh.shuati.common.ErrorCode;
import com.xh.shuati.exception.BusinessException;
import com.xh.shuati.model.dto.interview.InterviewMultiRequest;
import com.xh.shuati.model.dto.interview.InterviewRequest;
import com.xh.shuati.service.DummyInterviewService;
import com.xh.shuati.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/dummyinterview")
@Slf4j
public class DummyInterviewController {

    @PostMapping("/chatStream")
    public Flux<ServerSentEvent<String>> chatStream(@RequestBody InterviewRequest interviewRequest) {
        Long interviewId = interviewRequest.getInterviewId();
        String query = interviewRequest.getQuery();
        return dummyInterviewService.interviewStream(interviewId, query)
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk)
                        .build());
    }

    @PostMapping("/chatByMuitiStream")
    public Flux<ServerSentEvent<String>> chatMuitiStream(@RequestBody InterviewMultiRequest interviewMultiRequest) {
        Long interviewId = interviewMultiRequest.getInterviewId();
        String query = interviewMultiRequest.getQuery();
        String imagePath = interviewMultiRequest.getImagePath();
        if(!ImageUtils.isValidImage(imagePath)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片路径或格式错误");
        }

        return dummyInterviewService.interviewByMultiStream(interviewId, query, imagePath)
                .map(chunk -> ServerSentEvent.<String>builder()
                        .data(chunk)
                        .build());
    }

    @Resource
    private DummyInterviewService dummyInterviewService;

    @PostMapping("/chat")
    public String chat(@RequestBody InterviewRequest interviewRequest) {
        Long interviewId = interviewRequest.getInterviewId();
        String query = interviewRequest.getQuery();
        return dummyInterviewService.interview(interviewId, query);
    }

    @PostMapping("/chatByMuiti")
    public String chatMuiti(@RequestBody InterviewMultiRequest interviewMultiRequest) {
        Long interviewId = interviewMultiRequest.getInterviewId();
        String query = interviewMultiRequest.getQuery();
        String imagePath = interviewMultiRequest.getImagePath();
        if(!ImageUtils.isValidImage(imagePath)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片路径或格式错误");
        }
        return dummyInterviewService.interviewByMulti(interviewId, query, imagePath);
    }
}
